/*
 * This file is part of GuitarMaster.
 * 
 * GuitarMaster is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GuitarMaster is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.paris5.master2.guitarmaster.service;

import com.paris5.master2.guitarmaster.bean.*;
import com.paris5.master2.guitarmaster.dao.EcomDao;
import com.paris5.master2.guitarmaster.dao.EcomDaoService;
import com.paris5.master2.guitarmaster.dao.EcomQuery;
import com.paris5.master2.guitarmaster.entity.*;
import com.paris5.master2.guitarmaster.exception.EcomException;
import com.paris5.master2.guitarmaster.exception.EcomQueryException;
import com.paris5.master2.guitarmaster.exception.EcomValidationException;
import com.paris5.master2.guitarmaster.service.ServiceAdminRemote;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
/**
 *
 * @author Leticia Mahamed, Alice Khammy, mourad nedjahi, Saliou Mamadou Barry
 */
@Stateless(mappedName = "admin")
public class ServiceAdmin implements ServiceAdminRemote {

    @EJB
    private EcomDao sdao;
    @EJB private ServiceProductRemote serviceProduct;
    @EJB private ServiceCustomerRemote serviceCustomer;
    @EJB private BidTimerLocal bidTimer;
    //Identifiant de l'administrateur de la base.
    final int idAdmin=10;
    
    @Override
    public void addProduct(EcomProduct bean) throws EcomValidationException {
        if (bean == null) {
            throw new EcomValidationException("Empty Product sent ! (EcomProduct == null)");
        }
        Product product = new Product(bean);
        sdao.insert(product);
    }
    
    @Override
    public void addProductType(EcomProductType bean) throws EcomValidationException {
        if (bean == null) {
            throw new EcomValidationException("Empty ProductType sent ! (EcomProductType == null)");
        }
        ProductType productType = new ProductType(bean);
        sdao.insert(productType);
    }
    
    @Override
    public void updateProduct(EcomProduct bean) throws EcomValidationException {
        Product product=(Product)sdao.find(Product.class, bean.getIdProduct());
        
        if (bean == null) {
            throw new EcomValidationException("Empty Product sent ! (EcomProduct == null)");
        }
        product = UpDateProductFomEcomProduct(product,bean);
        sdao.update(product);
    }
    
    @Override
    public void addCategory(EcomCategory bean) throws EcomValidationException {
        if (bean == null) {
            throw new EcomValidationException("Empty category sent ! (EcomCategory == null)");
        }
        Category category = new Category(bean);
        sdao.insert(category);
    }
    
    @Override
    public void withdrawStoreBalance(EcomStore bean, Float amount) throws EcomValidationException {
        if (bean == null) {
            throw new EcomValidationException("Empty Store sent ! (EcomStory == null)");
        }
        Store store = (Store) sdao.find(Store.class, bean.getIdStore());
        if (store == null) {
            throw new EcomValidationException("This Store does not exist in data base");
        }
        Float oldBalance = store.getBalance();
        Float newBalance = oldBalance - amount;
        if (newBalance < 0) {
            throw new EcomValidationException("Requested amount exceeds the balance! impossible operation");
        }
        store.setBalance(newBalance);
        sdao.update(store);
    }
    
    @Override
    public void setProductToAuction(EcomProduct bean) throws EcomValidationException, EcomQueryException, EcomException {
        if (bean == null) {
            throw new EcomValidationException("Empty product sent ! (EcomProduct == null)");
        }
        Product product = (Product) sdao.find(Product.class, bean.getIdProduct());
        product.setBidEndDate(bean.getBidEndDate());
        
        serviceProduct.bid(10, product.getIdProduct(), product.getIdProductType().getPrice()+1); 
        System.out.println("LastBid est");
        ArrayList params = new ArrayList();
        Date now = new Date();
        params.add(product.getIdProduct());
        params.add(0);
        params.add(now);
        EcomQuery.PRODUCT_BIDS.setSelectQuery();
        EcomQuery.PRODUCT_BIDS.setQueryOrder(1, true);
        Bid lastBid = (Bid) sdao.execute(EcomQuery.PRODUCT_BIDS, params);
        System.out.println("LastBid est "+lastBid);
        sdao.update(product);
        
        if(lastBid!=null){
            bidTimer.creerBidTimer(lastBid);
       }
        
    }
    
    @Override
    public void addStore(EcomStore bean) throws EcomValidationException {
        if (bean == null) {
            throw new EcomValidationException("Empty Store sent ! (EcomStory == null)");
        }
        Store store = new Store(bean);
        sdao.insert(store);
    }
    
    @Override
    public void addCountry(EcomCountry bean) throws EcomValidationException {
        if (bean == null) {
            throw new EcomValidationException("Empty Country sent ! (EcomCountry == null)");
        }
        Country country = new Country(bean);
        sdao.insert(country);
    }
    
    @Override
    public Float getStoreBalance(EcomStore bean) throws EcomValidationException {
        
        Store store = (Store) sdao.find(Store.class, bean.getIdStore());
        if (store == null) {
            throw new EcomValidationException("This Store does not exist in data base");
        }
        return store.getBalance();
    }
    /**
     * Cette méthode permet de déposer de l'argent dans un magasin
     * @param bean : Le magasin à mettre à jour
     * @param amount Le montant à ajouter
     * @throws EcomValidationException 
     */
    @Override
    public void depositAmount(EcomStore bean, Float amount) throws EcomValidationException {
      if (bean == null) {
            throw new EcomValidationException("Empty Store sent ! (EcomStory == null)");
        }
        Store store = (Store) sdao.find(Store.class, bean.getIdStore());
        if (store == null) {
            throw new EcomValidationException("This Store does not exist in data base");
        }
        Float oldBalance = store.getBalance();
        Float newBalance = oldBalance + amount;
        if (newBalance < 0) {
            throw new EcomValidationException("Requested amount exceeds the balance! impossible operation");
        }
        store.setBalance(newBalance);
        sdao.update(store);  
    }
    /**
     * Cette méthode permet de finir une enchère.
     * @param bean
     * @throws EcomValidationException
     * @throws EcomQueryException
     * @throws EcomException 
     */
    @Override
    public void endProductToAuction(EcomProduct bean) throws EcomValidationException, EcomQueryException, EcomException {
        if (bean == null) {
            throw new EcomValidationException("Empty product sent ! (EcomProduct == null)");
        }
        Product product = (Product) sdao.find(Product.class, bean.getIdProduct());
        List<EcomBid> bids=serviceProduct.getProductBids(product.getIdProduct(), 0, 2);
        User lastUser=(User) sdao.find(User.class,bids.get(0).getUser().getId());
        Float price=product.getIdProductType().getPrice();
        try{
        if(bids!=null && lastUser.getIdUser()!=idAdmin && price<=lastUser.getBalance()){      
            serviceCustomer.withdrawUserBalance(lastUser.getIdUser(),price);
            this.depositAmount(product.getIdStore().getEcomStore(), price);
            product.setStatus(1);
            
        }else{
            if(bids.size()>0){
                Score score=lastUser.getScore();
                int oldScoreValue=score.getScore();
                int newScoreValue=oldScoreValue>0?oldScoreValue-1:0;
                score.setScore(newScoreValue);
                sdao.update(score);
                product.setBidEndDate(null);
            }
 
            sdao.update(product);
           
        }

        } catch(Exception e){
             e.printStackTrace();
         }
        
    }
    /**
     * 
     * @param product
     * @param eProduct
     * @return 
     */
    private Product UpDateProductFomEcomProduct(Product product, EcomProduct eProduct){
        product.setBidEndDate(eProduct.getBidEndDate());
        product.setStatus(eProduct.getStatus());
        ProductType productType=(ProductType)sdao.find(ProductType.class, eProduct.getIdProductType());
        product.setIdProductType(productType);
        product.setUpdateDate(eProduct.getUpdateDate());
        return product;    
    }

    
    
    
}
